package br.com.array.android.ma.service;

import android.os.AsyncTask;
import br.com.array.android.ma.model.Notificacao;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by leonardo.neves on 06/08/2014.
 */
public class AsyncTaskNotificacao extends AsyncTask<QueryParam, Void, List<Notificacao>> {

    private ServiceNotificacaoListener listener;
    private NotificacaoException exception;

    public AsyncTaskNotificacao(ServiceNotificacaoListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<Notificacao> doInBackground(QueryParam... params) {
        HttpRequest request = new HttpRequest(params[0]);

        String json;
        try {
            json = request.getUrlResponse();

            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(json).getAsJsonArray();

            List<Notificacao> notificacaos = new ArrayList<Notificacao>();

            for (JsonElement element : jsonArray){
                Notificacao notificacao = gson.fromJson(element, Notificacao.class);
                notificacaos.add(notificacao);
            }
            return notificacaos;

        } catch (Exception e){
            exception = new NotificacaoException(e.getMessage());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<Notificacao> notificacaos) {
        super.onPostExecute(notificacaos);
        if (this.listener != null && exception == null){
            this.listener.onSucesso(notificacaos);
        }
        if (this.listener != null && this.exception != null){
            this.listener.onErro(exception);
        }
    }
}
